#include "emailservice.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <iostream>
using namespace com_oocl_monitor::service;
using namespace com_oocl_monitor::system;
using namespace com_oocl_monitor::domain;
using namespace boost::posix_time;


EmailService::EmailService(EmailConfig emailConfig,
	FtpInfo ftpInfo, Profile profile,DataCollection* dataList)
	:_emailConfig(emailConfig),_ftpInfo(ftpInfo),_profile(profile),_dataList(dataList){
		_curlEnv=CurlEnv::getInstance();
}

EmailService::~EmailService(){
	if(_dataList!=nullptr)
		delete(_dataList);
}

void EmailService::run(){
	UserData userData;
	string msg=createMSG();
	userData.ss.write(msg.c_str(),msg.length());
	userData.total=msg.length();
	CURL *handler=curl_easy_init();
	curl_slist *r=NULL;
	if(handler){
		for(auto i=_emailConfig.toList.cbegin();i!=_emailConfig.toList.cend();i++){
			string rec="<"+(*i)+">";
			r=curl_slist_append(r,rec.c_str());
		}
		string mf="<"+_emailConfig._from+">";
		curl_easy_setopt(handler,CURLOPT_URL,_emailConfig._server.c_str());
		if(_emailConfig._port != ""){
			stringstream ss(_emailConfig._port);
			long port;
			ss>>port;
			curl_easy_setopt(handler,CURLOPT_PORT,port);
		}
		if(_emailConfig._usr!="" && _emailConfig._pwd!=""){
			curl_easy_setopt(handler,CURLOPT_USERNAME,_emailConfig._usr.c_str());
			curl_easy_setopt(handler,CURLOPT_PASSWORD,_emailConfig._pwd.c_str());

		}
		curl_easy_setopt(handler,CURLOPT_READFUNCTION,payload_source);
		curl_easy_setopt(handler,CURLOPT_READDATA,&userData);
		curl_easy_setopt(handler,CURLOPT_UPLOAD,1L);
		//        curl_easy_setopt(handler, CURLOPT_VERBOSE, 1L);
		//        curl_easy_setopt(handler, CURLOPT_USE_SSL, (long) CURLUSESSL_ALL);
		//        curl_easy_setopt(handler, CURLOPT_SSL_VERIFYPEER, 0L);
		//        curl_easy_setopt(handler, CURLOPT_SSL_VERIFYHOST, 0L);
		//        curl_easy_setopt(handler, CURLOPT_SSLVERSION, 0L);
		//        curl_easy_setopt(handler, CURLOPT_SSL_SESSIONID_CACHE, 0L);
		curl_easy_setopt(handler, CURLOPT_NOSIGNAL, 1L);
		curl_easy_setopt(handler,CURLOPT_MAIL_FROM,mf.c_str());
		curl_easy_setopt(handler,CURLOPT_MAIL_RCPT,r);
		curl_easy_perform(handler);
	}
	curl_slist_free_all(r);
	curl_easy_cleanup(handler);
}

string EmailService::createMSG() const{
	ptime now=second_clock::local_time();
	time_facet *f=new time_facet("%Y-%m-%d %H:%M:%S");
	stringstream ss;
	ss.imbue(std::locale(std::cout.getloc(),f));
	ss<<now;
	string dateTime;
	getline(ss,dateTime);
	boost::trim(dateTime);
	string payload="Date:"+dateTime+"\r\n";
	for(auto i=_emailConfig.toList.cbegin();i!=_emailConfig.toList.cend();i++){
		payload+="To:<"+(*i)+">\r\n";
	}
	payload+="From:<"+_emailConfig._from+">\r\n";
	payload+="Subject:["+_profile._project+"]FTP MONITOR ALARM\r\n";
	payload+="\r\n";
	payload+="FTP\r\n";
	payload+="\tHOST: "+_ftpInfo._host+" \r\n";
	payload+="\tPort: "+(_ftpInfo._port==""?"21":_ftpInfo._port)+" \r\n";
	payload+="\tURI: "+_profile._uri+"\r\n";
	payload+="\tUSR: "+_ftpInfo._usr+" \r\n";
	payload+="\tPWD: "+_ftpInfo._pwd+" \r\n";
	payload+="PROFILE\r\n";
	payload+="\tProfile Name: "+_profile._profileName+" \r\n";
	payload+="\tWarehouse: "+_profile._warehouse+" \r\n";
	payload+="\tOwner: "+_profile._owner+" \r\n";
	payload+="\tOrderType: "+_profile._orderType+" \r\n";
	if(_dataList == nullptr || _dataList->isEmpty()){
		payload+="!!!!!!DB OR FTP ERROR!!!!!!\r\n";
	}
	else{
		payload+="=========================Mis-Match File List============================\r\n ";
		payload+=_dataList->toString();
	}
	return payload;
}
size_t EmailService::payload_source(char *ptr, size_t size, size_t nmenb, void *usrp){
	UserData *ud=static_cast<UserData*>(usrp);
	if(ud->ss.eof()){
		return 0;
	}
	size_t before=ud->ss.tellg();
	ud->ss.read(ptr,size*nmenb);
	size_t after=ud->ss.tellg();
	if(ud->ss.eof()){
		return ud->total-before;
	}
	return after-before;
}

